﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Slippor.Douban.Radio.Assist;
using Slippor.Douban.Radio.BaseForm;

namespace LocalTrackerData
{
    public partial class TrackForm : Form
    {
        public TrackForm()
        {
            InitializeComponent();
            TopMost = true;
            dataGridView.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;

            RefreshDataTable = songTrackerTableAdapter.Fill;
            dataGridView.Columns["fav"].DefaultCellStyle.NullValue = Properties.Resources.UnFav;

            dataGridView.CellContentClick += new DataGridViewCellEventHandler(dataGridView_CellContentClick);
            dataGridView.CellContentDoubleClick += new DataGridViewCellEventHandler(dataGridView_CellContentDoubleClick);
            dataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView_CellFormatting);
            dataGridView.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView_DataBindingComplete);
        }

        #region DataGridView
        private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int row = 0; row < dataGridView.Rows.Count; row++)
            {
                DataGridViewRow currentDGRow = this.dataGridView.Rows[row];
                DataRowView rowView = currentDGRow.DataBoundItem as DataRowView;
                //currentDGRow.Cells["index"].Value = String.Format("{0:D4}", row + 1);
                #region 设置图片
                DataGridViewCell favImageCell = currentDGRow.Cells["fav"];
                bool fav = (bool)rowView["favstate"];
                favImageCell.ToolTipText = fav ? "取消'我喜欢'" : "我喜欢";
                if (fav)
                {
                    Bitmap thumb = Properties.Resources.Fav;
                    favImageCell.Value = thumb;
                }
                #endregion

                #region 设置命令
                DataGridViewCell commandCell = currentDGRow.Cells["command"];
                try
                {
                    Command command = (Command)rowView["command"];
                    switch (command)
                    {
                        case Command.Del:
                            commandCell.Value = "x";
                            commandCell.ToolTipText = "删除";
                            break;
                        case Command.Next:
                            commandCell.Value = "→";
                            commandCell.ToolTipText = "跳过";
                            break;
                        case Command.Filter:
                            commandCell.Value = "v";
                            commandCell.ToolTipText = "过滤";
                            break;
                        default:
                            commandCell.Value = String.Empty;
                            break;
                    }
                }
                catch
                {
                    commandCell.Value = String.Empty;
                }
                #endregion
            }
        }

        private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex != 0)
            {
                return;
            }
            DataGridViewRow currentDGRow = this.dataGridView.Rows[e.RowIndex];
            currentDGRow.Cells["index"].Value = String.Format("{0}", (_currentPage-1)*_pageSize + e.RowIndex + 1);
        }

        internal SetFav SetFav;

        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.RowIndex <0 || e.ColumnIndex <= 0)
            {
                return;
            }
            DataGridViewRow currentDGRow = this.dataGridView.Rows[e.RowIndex];
            DataRowView rowView = currentDGRow.DataBoundItem as DataRowView;
            if(dataGridView.Columns[e.ColumnIndex].Name == "atitle")
            {
                object aid = rowView["aid"];
                using(BackgroundWorker worker = new BackgroundWorker())
                {
                    worker.DoWork += (senderW, eW) =>
                        {
                            RadioUtility.Browse(String.Format("http://music.douban.com/subject/{0}/", aid));
                        };
                    worker.RunWorkerAsync();
                }
            }
            else if (dataGridView.Columns[e.ColumnIndex].Name == "fav")
            {
                bool fav = (bool)rowView["favstate"];
                Song song = new Song()
                {
                    FaveState = fav ? FavState.Fav : FavState.UnFav,
                    Title = rowView["stitle"].ToString(),
                    ListenTime = (DateTime)rowView["ldate"],
                    SongID = rowView["sid"].ToString()
                };
                if(SetFav != null)
                {
                    SetFav(song, (ref Song newSong)=>
                        {
                            if((newSong.FaveState == FavState.Fav) != fav)
                            {
                                RefreshTable();
                            }
                        });
                }
            }
        }

        private void dataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex <= 0)
            {
                return;
            }
            DataGridViewRow currentDGRow = this.dataGridView.Rows[e.RowIndex];
            DataRowView rowView = currentDGRow.DataBoundItem as DataRowView;
            String name = dataGridView.Columns[e.ColumnIndex].Name;
            switch (name)
            {
                case "artists":
                case "stitle":
                case "adate":
                    String keyword = rowView[name].ToString();
                    SetKeywordFilter(keyword, name);
                    break;
                default:
                    break;
            }
        }
        #endregion

        private void RefreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshTable();
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Clipboard.SetDataObject(dataGridView.GetClipboardContent());
            }
            catch
            {
                ;
            }
        }

        private void FavToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (toolStripButtonFav.Text)
            {
                case "喜欢的":
                    toolStripButtonFav.Text = "全部";
                    dataGridView.Columns["fav"].DefaultCellStyle.NullValue = Properties.Resources.Fav;
                    break;
                case "全部":
                    toolStripButtonFav.Text = "喜欢的";
                    dataGridView.Columns["fav"].DefaultCellStyle.NullValue = Properties.Resources.UnFav;
                    break;
            }
            SetRefreshTable();
            RefreshTable();
        }

        private void SetRefreshTable()
        {
            switch (toolStripButtonFav.Text)
            {
                case "全部":
                    RefreshDataTable = this.songTrackerTableAdapter.FillFav;
                    break;
                case "喜欢的":
                    RefreshDataTable = this.songTrackerTableAdapter.Fill;
                    break;
            }
        }

        private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
        }

        private void TrackForm_Load(object sender, EventArgs e)
        {
            RefreshTable();
        }

        #region RefreshData
        private RefreshData RefreshDataTable;
        private void RefreshTable()
        {
            RefreshDataTable(this.radioLocalDataSet.SongTracker);
            SetData();
            RefreshStatus();
        }

        private void RefreshStatus()
        {
            using (BackgroundWorker refreshWorker = new BackgroundWorker())
            {
                refreshWorker.DoWork += (sender, e) =>
                {
                    e.Result = GetStatusText();
                };
                refreshWorker.RunWorkerCompleted += (sender, e) =>
                {
                    toolStripStatusLabelSummary.Text = e.Result.ToString();
                };
                refreshWorker.RunWorkerAsync();
            }
        }

        private DataSetHelper _helper = new DataSetHelper();
        private String GetStatusText()
        {
            int totalListen = 0, totalSong = 0, totalAlbum = 0, totalArtists = 0;
            int totalDel = 0, totalNext = 0, totalFilter = 0;
            totalListen = radioLocalDataView.Count;
            DataTable dataViewTable = radioLocalDataView.ToTable();
            totalSong = _helper.SelectDistinctCount(dataViewTable, "sid");
            totalAlbum = _helper.SelectDistinctCount(dataViewTable, "aid");
            totalArtists = _helper.SelectDistinctCount(dataViewTable, "artists");
            totalDel = Convert.ToInt32(dataViewTable.Compute("COUNT(stitle)", "command = 361"));
            totalNext = Convert.ToInt32(dataViewTable.Compute("COUNT(stitle)", "command = 362"));
            totalFilter = Convert.ToInt32(dataViewTable.Compute("COUNT(stitle)", "command = 367"));
            return String.Format("共{0:N0}歌次,{1:N0}首歌曲,{2:N0}张专辑,{3:N0}位表演者 | 跳过{4:N0}次,删除 {5:N0}首,过滤{6:N0}首", totalListen, totalSong, totalAlbum, totalArtists, totalNext, totalDel, totalFilter);
        }
        #endregion

        #region 分页
        private int _currentPage = 1;
        private int _pageSize = 20;
        private int _totalPage = 0;
        private void SetData()
        {
            //int totalRow = radioLocalDataSet.SongTracker.Rows.Count;
            //_totalPage = totalRow / _pageSize;
            //if (_totalPage * _pageSize < totalRow)
            //{
            //    _totalPage++;
            //}
            //if (_totalPage < _currentPage)
            //{
            //    _currentPage = _totalPage;
            //}
            //bindingNavigator.CountItem.Text = String.Format("/{0}", _totalPage);
            //bindingNavigator.PositionItem.Text = _currentPage.ToString();
            //bindingNavigator.MoveFirstItem.Enabled = _currentPage > 1;
            //bindingNavigator.MovePreviousItem.Enabled = _currentPage > 1;
            //bindingNavigator.MoveLastItem.Enabled = _currentPage < _totalPage;
            //bindingNavigator.MoveNextItem.Enabled = _currentPage < _totalPage;

            //DataTable dtTemp = radioLocalDataSet.SongTracker.Clone();   //克隆DataTable结构框架
            //int start = (_currentPage - 1) * _pageSize;   //当前页面开始记录行
            //int end = 0;     //当前页面结束记录行
            //if (_currentPage == _totalPage)
            //{
            //    end = totalRow;
            //}
            //else
            //{
            //    end = _currentPage * _pageSize;
            //}
            //for (int i = start; i < end; i++)
            //{
            //    dtTemp.ImportRow(radioLocalDataSet.SongTracker.Rows[i]);
            //}
            //radioLocalDataView.Table = dtTemp;
        }

        private void bindingNavigator_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //if(e.ClickedItem == bindingNavigator.MovePreviousItem)
            //{
            //    if(_currentPage > 1)
            //    {
            //        _currentPage--;
            //        SetData();
            //    }
            //}
            //else if(e.ClickedItem == bindingNavigator.MoveNextItem)
            //{
            //    if (_currentPage < _totalPage)
            //    {
            //        _currentPage++;
            //        SetData();
            //    }
            //}
            //else if (e.ClickedItem == bindingNavigator.MoveFirstItem)
            //{
            //    _currentPage = 1;
            //    SetData();
            //}
            //else if (e.ClickedItem == bindingNavigator.MoveLastItem)
            //{
            //    _currentPage = _totalPage;
            //    SetData();
            //}
        }
        #endregion

        #region 搜索
        private void toolStripSplitButtonSearch_ButtonClick(object sender, EventArgs e)
        {
            SearchKeyword();
        }

        private void toolStripTextBoxSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            //SearchKeyword();
        }

        private void toolStripTextBoxSearch_KeyUp(object sender, KeyEventArgs e)
        {
            //SearchKeyword();
        }

        private void toolStripTextBoxSearch_TextChanged(object sender, EventArgs e)
        {
            SearchKeyword();
        }

        private readonly String _filterKeyword = "atitle LIKE  '%{0}%' OR artists LIKE '%{0}%' OR stitle LIKE '%{0}%'";
        private void SetKeywordFilter(String keyword, String column)
        {
            String key = "keyword";
            keyword = keyword.Replace("'", "''");
            if (!String.IsNullOrEmpty(keyword))
            {
                switch (column)
                {
                    case "all":
                        _filters[key] = String.Format(_filterKeyword, keyword);
                        break;
                    case "adate":
                        short year = -1;
                        Int16.TryParse(keyword, out year);
                        _filters[key] = String.Format("[adate] = {0}", year);
                        break;
                    default:
                        _filters[key] = String.Format("{1} LIKE '%{0}%'", keyword, column);
                        break;
                }
            }
            else
            {
                _filters[key] = String.Empty;
            }
            SetFilters();
        }

        private ToolStripMenuItem _currentSearchItem = null;
        private void toolStripSplitButtonSearch_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (_currentSearchItem == null)
            {
                _currentSearchItem = searchToolStripMenuItem;
            }
            ToolStripMenuItem item = (e.ClickedItem as ToolStripMenuItem);
            if (_currentSearchItem != item)
            {
                _currentSearchItem.Checked = false;
                _currentSearchItem = item;
                _currentSearchItem.Checked = true;
                toolStripSplitButtonSearch.Text = _currentSearchItem.Text;
            }
            SearchKeyword();
        }

        private void SearchKeyword()
        {
            string column = "";
            if (_currentSearchItem == songToolStripMenuItem)
            {
                column = "stitle";
            }
            else if (_currentSearchItem == albumToolStripMenuItem)
            {
                column = "atitle";
            }
            else if (_currentSearchItem == artistsToolStripMenuItem)
            {
                column = "artists";
            }
            else if (_currentSearchItem == yearToolStripMenuItem)
            {
                column = "adate";
            }
            else
            {
                column = "all";
            }
            SetKeywordFilter(toolStripTextBoxSearch.Text, column);
        }
        #endregion

        #region 时间筛选
        private ToolStripMenuItem _currentDateTimeItem = null;
        private void toolStripSplitButtonDateTime_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if(_currentDateTimeItem == null)
            {
                _currentDateTimeItem = allToolStripMenuItem;
            }
            ToolStripMenuItem item = (e.ClickedItem as ToolStripMenuItem);
            if(_currentDateTimeItem != item)
            {
                _currentDateTimeItem.Checked = false;
                _currentDateTimeItem = item;
                _currentDateTimeItem.Checked = true;
                toolStripSplitButtonDateTime.Text = _currentDateTimeItem.Text;
                string key = "Date";
                DateTime today = DateTime.Today;
                if(_currentDateTimeItem == todayToolStripMenuItem)
                {
                    _filters[key] = String.Format("[ldate] >= '{0}'", today);
                }
                else if (_currentDateTimeItem == yesterdayToolStripMenuItem)
                {
                    _filters[key] = String.Format("[ldate] >= '{0}' AND [ldate] < '{1}'", today.AddDays(-1), today);
                }
                else if (_currentDateTimeItem == sevenDaysToolStripMenuItem)
                {
                    _filters[key] = String.Format("[ldate] >= '{0}'", today.AddDays(-7));
                }
                else if (_currentDateTimeItem == monthToolStripMenuItem)
                {
                    _filters[key] = String.Format("[ldate] >= '{0}'", new DateTime(today.Year, today.Month, 1));
                }
                else if (_currentDateTimeItem == allToolStripMenuItem)
                {
                    _filters[key] = String.Empty;
                }
                SetFilters();
            }
        }
        #endregion

        private Dictionary<String, String> _filters = new Dictionary<String, String>();
        private void SetFilters()
        {
            String totalFilter = String.Empty;
            foreach (String filter in _filters.Values)
            {
                if(!String.IsNullOrEmpty(filter))
                {
                    totalFilter += String.Format("AND ({0})", filter);
                }
            }
            if(totalFilter.Length >= 4)
            {
                totalFilter = totalFilter.Remove(0, 4);
            }
            radioLocalDataView.RowFilter = totalFilter;
            RefreshStatus();
        }

        private void dataGridView_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {

        }

    }

    internal delegate void SetFav(Song song, PostFresh refreshedFav);

    internal delegate int RefreshData(LocalTrackerData.RadioLocalDataSet.SongTrackerDataTable dataTable);
}
